package com.seal.commons.query;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-06-21 12:05<br/>
 * @since JDK 1.8
 */
@Slf4j
public class DefaultQueryHandlerFactory implements FactoryBean {

    private QueryHandler queryHandler;

    @Override
    public Object getObject() throws Exception {
        return queryHandler;
    }

    public void setAdapterConfigLocations(List<Resource> adapterConfigLocations) {
        BeanDefinitionRegistry definitionRegistry = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(definitionRegistry);
        for (Resource resource : adapterConfigLocations) {
            log.debug("resources:["+resource+"]");
            reader.loadBeanDefinitions(resource);
        }
        BeanFactory factory = (BeanFactory) definitionRegistry;
        Map adapters = new HashMap();
        for(String beanName: definitionRegistry.getBeanDefinitionNames()){
            log.info("beanName is {}",beanName);
            if(factory.isTypeMatch(beanName, Map.class)){
                try{
                    Map map = factory.getBean(beanName, Map.class);
                    if(map!=null){
                        adapters.putAll(map);
                    }
                }catch (BeansException e){
                    log.error("" ,e);
                }
            }
        }
        DefaultQueryHandler defaultQueryHandler = new DefaultQueryHandler();
        defaultQueryHandler.setAdapers(adapters);
        queryHandler = defaultQueryHandler;
    }

    @Override
    public Class<?> getObjectType() {
        return QueryHandler.class;
    }


}